#!/usr/bin/env bash
set -euo pipefail

LOG=${1:-/tmp/audit-demo.log}
SEAL="$LOG.seal"

echo "[1] 生成测试日志..."
mkdir -p "$(dirname "$LOG")"
cat > "$LOG" <<'EOF'
line-1
line-2
line-3
EOF

echo "[2] 生成/检测 SM2 P12 和 salt..."
if [[ ! -f /etc/pki/audit/sm2.p12 || ! -f /etc/pki/audit/p12_salt ]]; then
  echo "请先运行 tools/audit-keygen/audit-keygen 创建 P12 和 salt"
  exit 1
fi

echo "[3] 封装签名..."
# 如已实现 AUDIT_P12_PASSHEX 环境变量支持，取消注释下一行并设置值
# export AUDIT_P12_PASSHEX=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
../audit-seal "$LOG"

echo "[4] 校验应成功..."
../audit-verify "$SEAL" || { echo "校验失败"; exit 1; }

echo "[5] 篡改日志（追加），校验应失败并报警..."
echo "tampered" >> "$LOG"
set +e
../audit-verify "$SEAL"
RET=$?
set -e
if [[ $RET -eq 0 ]]; then
  echo "预期失败但成功了，异常"
  exit 2
else
  echo "如配置 alarm，可在 syslog/journal 或 /var/log/audit-gm/alarm.log 查告警"
fi

echo "[6] 恢复日志，重新封装并验证成功..."
# 重新写回原始内容
cat > "$LOG" <<'EOF'
line-1
line-2
line-3
EOF
../audit-seal "$LOG"
../audit-verify "$SEAL"

echo "[7] 篡改 seal 签名，校验应失败..."
cp "$SEAL" "$SEAL.bak"
sed -i 's/sig_base64=.*/sig_base64=AAAA/g' "$SEAL"
set +e
../audit-verify "$SEAL"
RET=$?
set -e
mv "$SEAL.bak" "$SEAL"
if [[ $RET -eq 0 ]]; then
  echo "预期失败但成功了，异常"
  exit 3
fi

echo "[8] 启动 watcher（后台），自动封装测试..."
../audit-watch "$LOG" &
WPID=$!
sleep 1
echo "new line" >> "$LOG"
sleep 1
kill $WPID

echo "[9] 再次验证成功..."
../audit-verify "$SEAL" || { echo "校验失败"; exit 4; }

echo "[OK] 全部测试通过"

